package mysql

import "gorm.io/gorm"

// Order 订单表
type Order struct {
	gorm.Model
	UserId  int     `gorm:"type:int;index;not null;comment:用户id"`
	OrderSn string  `gorm:"type:char(36);unique;not null;comment:订单号"`
	PayType int     `gorm:"type:tinyint;default:1;comment:支付类型:1:支付宝;2:微信"`
	Status  int     `gorm:"type:tinyint(1);default:1;comment:订单状态:1:待支付;2:已支付;3:已取消;4:已退款;5:已完成"`
	PayTime int     `gorm:"type:int;comment:支付时间"`
	Amount  float64 `gorm:"type:decimal(10,2);default:0.00;comment:订单金额"`
}

type OrderGoods struct {
	gorm.Model
	OrderId    int     `gorm:"type:int;index;not null;comment:订单id"`
	GoodsId    int     `gorm:"type:int;index;not null;comment:商品id"`
	GoodsTitle string  `gorm:"type:varchar(100);not null;comment:商品标题"`
	Num        int     `gorm:"type:int;not null;comment:商品数量"`
	Price      float64 `gorm:"type:decimal(10,2);not null;comment:商品单价"`
	GoodsCover string  `gorm:"type:varchar(200);not null;comment:商品封面"`
}

func CreateOrder(db *gorm.DB, o *Order, og *OrderGoods) error {
	// 再唠叨一下，事务一旦开始，你就应该使用 tx 处理数据
	tx := db.Begin()
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
		}
	}()

	if err := tx.Error; err != nil {
		return err
	}

	if err := tx.Create(&o).Error; err != nil {
		tx.Rollback()
		return err
	}
	og.OrderId = int(o.ID)

	if err := tx.Create(&og).Error; err != nil {
		tx.Rollback()
		return err
	}

	return tx.Commit().Error
}

func (o *Order) Create() error {
	return Db.Create(&o).Error
}

func (og *OrderGoods) Create() error {
	return Db.Create(&og).Error
}
